package com.ali.common;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class HmacUtil {
    private static final String ALGORITHM = "HmacMD5";

    /**
     * 获取Key
     */
    public static String getKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
            SecretKey secretKey = keyGenerator.generateKey();
            return Base64Util.encrypt(secretKey.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * HMAC加密
     */
    public static String encrypt(String content, String key) {
        byte[] contentByte = content.getBytes(StandardCharsets.UTF_8);

        try {
            Mac mac = getMac(key);
            byte[] doFinalByte = mac.doFinal(contentByte);
            return Base64Util.encrypt(doFinalByte);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Mac getMac(String key) {
        byte[] keyByte = Base64Util.getByteByDecrypt(key);

        try {
            SecretKey secretKey = new SecretKeySpec(keyByte, ALGORITHM);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return mac;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}